/**
 * 代理服务 - 用于解决CORS问题
 * 利用Umi的代理功能转发请求到Ollama服务器
 */

import axios from 'axios';

class ProxyService {
  private useProxy: boolean;
  private baseUrl: string;
  private proxyUrl: string;

  constructor() {
    this.useProxy = localStorage.getItem('useOllamaProxy') === 'true';
    this.baseUrl = localStorage.getItem('ollamaBaseUrl') || 'http://localhost:11434';
    this.proxyUrl = '/api/proxy'; // 这个URL会被Umi代理转发
  }

  setUseProxy(use: boolean): void {
    this.useProxy = use;
    localStorage.setItem('useOllamaProxy', use.toString());
  }

  getUseProxy(): boolean {
    return this.useProxy;
  }

  setBaseUrl(url: string): void {
    this.baseUrl = url;
    localStorage.setItem('ollamaBaseUrl', url);
  }

  getBaseUrl(): string {
    return this.baseUrl;
  }

  /**
   * 获取实际使用的URL
   * 如果启用代理，会使用代理URL
   * 否则直接使用baseUrl
   */
  getEffectiveUrl(): string {
    return this.useProxy ? this.proxyUrl : this.baseUrl;
  }

  /**
   * 根据配置更新代理设置
   */
  updateProxyConfig(): void {
    // 仅在需要时动态修改Umi的代理配置
    if (this.useProxy) {
      // 实际上Umi的代理配置是在编译时确定的
      // 这里我们只是更新本地存储中的值
      localStorage.setItem('ollamaProxyTarget', this.baseUrl);
    }
  }

  /**
   * 测试连接
   */
  async testConnection(url: string): Promise<{ success: boolean; message: string; details?: any }> {
    try {
      // 直接测试给定URL
      const response = await fetch(`${url}`, { 
        method: 'GET',
        headers: { 'Accept': 'application/json' }
      });
      
      if (!response.ok) {
        return {
          success: false,
          message: `服务器返回错误状态码: ${response.status}`,
          details: { status: response.status }
        };
      }
      
      return {
        success: true,
        message: '连接成功',
        details: { status: response.status }
      };
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : String(error),
        details: { error }
      };
    }
  }
}

export const proxyService = new ProxyService();
export default proxyService; 